package com.feng.service;

import com.feng.dao.BaseDao;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.List;

public abstract class BaseService<T> {
	
	 protected BaseDao<T> baseDao;
	 Class clazz;
	 
	 public BaseService() {
		super();
		System.out.println("当前子类对象:"+this);
		System.out.println("当前子类this对象相应的类型:"+this.getClass());
		System.out.println("当前类型的父类型信息(并不包括交类型参数信息):"+this.getClass().getSuperclass());
		System.out.println("当前类型的父类型信息(包括交类型参数信息):"+this.getClass().getGenericSuperclass());
		ParameterizedType type =(ParameterizedType) this.getClass().getGenericSuperclass();
		clazz =  (Class)type.getActualTypeArguments()[0];
		System.out.println(clazz);
	 }
	@PostConstruct
	 public void init() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException{
		 System.out.println("BaseService init()");
		String clazzName = clazz.getSimpleName();
		System.out.println(clazzName);
		String clazzDaoName = clazzName.substring(0,1).toLowerCase()+clazzName.substring(1)+"Dao";
		System.out.println(clazzDaoName);
		Field daoNameField = this.getClass().getDeclaredField(clazzDaoName);
		System.out.println(daoNameField.getName());
		Object object = daoNameField.get(this);
		System.err.println(object);
		
		Field baseDaoNameField = this.getClass().getSuperclass().getDeclaredField("baseDao");
		baseDaoNameField.set(this, object);
	 }
	@Transactional
	public void saveOrUpdate(T one) throws Exception{
		baseDao.saveOrUpdate(one);
	}

	@Transactional
	public void update(T one) throws Exception{
		baseDao.update(one);
	}
	
	@Transactional
	public void save(T one) throws Exception{
		baseDao.save(one);
	}

	@Transactional
	public void truncate() throws Exception{
		baseDao.truncate();
	}

	@Transactional
	public void save(List<T> many) throws Exception{
		baseDao.save(many);
	}
	
	@Transactional
	public void saveOrUpdate(List<T> many) throws Exception{
		baseDao.saveOrUpdate(many);
	}
	
	@Transactional
	public void delete(T one) throws Exception{
		baseDao.delete(one);
	}
	
	@Transactional
	public void del(Long id) throws Exception{
		baseDao.del(id);
	}
	
	@Transactional
	public void del(List<Long> ids) throws Exception{
		baseDao.del(ids);
	}
	
	
	@Transactional(readOnly = true)
	public T get(Long id)throws Exception{
		return baseDao.get(id);
	}
	
	
	
}
